<template>
  <div class="subscription-management">
    <div class="operation-bar">
      <div class="search-filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户或文档..."
          style="width: 300px"
          clearable
          @keyup.enter="searchSubscriptions"
        >
          <template #append>
            <el-button :icon="Search" @click="searchSubscriptions"></el-button>
          </template>
        </el-input>
        <el-select v-model="subscriptionType" placeholder="订阅类型" clearable @change="filterByType">
          <el-option label="文档订阅" value="document"></el-option>
          <el-option label="分类订阅" value="category"></el-option>
          <el-option label="标签订阅" value="tag"></el-option>
        </el-select>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="subscriptions.length === 0" class="empty-container">
      <el-empty description="暂无订阅数据" />
    </div>
    
    <el-table v-else :data="subscriptions" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户" width="150"></el-table-column>
      <el-table-column label="订阅类型" width="120">
        <template #default="scope">
          <el-tag :type="getTypeTagType(scope.row.type)">
            {{ getTypeName(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="targetName" label="订阅对象"></el-table-column>
      <el-table-column label="订阅时间" width="180">
        <template #default="scope">
          {{ new Date(scope.row.subscribeTime).toLocaleString() }}
        </template>
      </el-table-column>
      <el-table-column label="最近通知" width="180">
        <template #default="scope">
          {{ scope.row.lastNotifyTime ? new Date(scope.row.lastNotifyTime).toLocaleString() : '暂无' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="viewSubscriptionDetail(scope.row)">查看</el-button>
          <el-button size="small" type="danger" @click="deleteSubscription(scope.row.id)">删除</el-button>
          <el-button size="small" type="primary" @click="sendTestNotification(scope.row.id)">测试通知</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container" v-if="total > 0">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订阅详情对话框 -->
    <el-dialog v-model="subscriptionDetailVisible" title="订阅详情" width="40%">
      <div v-if="currentSubscription">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="ID">{{ currentSubscription.id }}</el-descriptions-item>
          <el-descriptions-item label="用户">{{ currentSubscription.username }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentSubscription.userId }}</el-descriptions-item>
          <el-descriptions-item label="订阅类型">{{ getTypeName(currentSubscription.type) }}</el-descriptions-item>
          <el-descriptions-item label="订阅对象">{{ currentSubscription.targetName }}</el-descriptions-item>
          <el-descriptions-item label="对象ID">{{ currentSubscription.targetId }}</el-descriptions-item>
          <el-descriptions-item label="订阅时间">{{ new Date(currentSubscription.subscribeTime).toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="最近通知">{{ currentSubscription.lastNotifyTime ? new Date(currentSubscription.lastNotifyTime).toLocaleString() : '暂无' }}</el-descriptions-item>
          <el-descriptions-item label="通知次数">{{ currentSubscription.notifyCount || 0 }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-actions">
          <el-button type="primary" @click="sendTestNotification(currentSubscription.id)">发送测试通知</el-button>
          <el-button type="danger" @click="deleteSubscription(currentSubscription.id); subscriptionDetailVisible = false">删除订阅</el-button>
        </div>
        
        <!-- 最近通知历史 -->
        <div class="notification-history" v-if="notificationHistory.length > 0">
          <h3>最近通知历史</h3>
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in notificationHistory"
              :key="index"
              :timestamp="new Date(activity.time).toLocaleString()"
              :type="activity.status === 'success' ? 'success' : 'danger'"
            >
              {{ activity.content }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 搜索和分页
const searchQuery = ref('')
const subscriptionType = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 数据和加载状态
const loading = ref(true)
const subscriptions = ref([])
const currentSubscription = ref(null)
const notificationHistory = ref([])

// 对话框控制
const subscriptionDetailVisible = ref(false)

// 初始化
onMounted(() => {
  fetchSubscriptions()
})

// 获取订阅列表
async function fetchSubscriptions() {
  loading.value = true
  try {
    // 这里替换为实际的API调用
    // const response = await axios.get('/api/admin/subscriptions', {
    //   params: {
    //     page: currentPage.value,
    //     size: pageSize.value,
    //     query: searchQuery.value,
    //     type: subscriptionType.value
    //   }
    // })
    
    // 模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    subscriptions.value = Array.from({ length: 10 }, (_, i) => {
      const types = ['document', 'category', 'tag']
      const type = types[Math.floor(Math.random() * types.length)]
      return {
        id: i + 1,
        userId: Math.floor(Math.random() * 100) + 1,
        username: `user${Math.floor(Math.random() * 20) + 1}`,
        type: type,
        targetId: Math.floor(Math.random() * 50) + 1,
        targetName: type === 'document' ? `文档 ${i + 1}` : type === 'category' ? `分类 ${i + 1}` : `标签 ${i + 1}`,
        subscribeTime: new Date().getTime() - Math.floor(Math.random() * 10000000),
        lastNotifyTime: Math.random() > 0.3 ? new Date().getTime() - Math.floor(Math.random() * 5000000) : null,
        notifyCount: Math.floor(Math.random() * 20)
      }
    })
    
    // 根据筛选条件过滤
    if (subscriptionType.value) {
      subscriptions.value = subscriptions.value.filter(item => item.type === subscriptionType.value)
    }
    
    total.value = 100 // 模拟总数
  } catch (error) {
    console.error('Failed to fetch subscriptions:', error)
    ElMessage.error('获取订阅列表失败')
  } finally {
    loading.value = false
  }
}

// 获取类型显示名称
function getTypeName(type) {
  switch (type) {
    case 'document':
      return '文档订阅'
    case 'category':
      return '分类订阅'
    case 'tag':
      return '标签订阅'
    default:
      return '未知类型'
  }
}

// 获取标签类型
function getTypeTagType(type) {
  switch (type) {
    case 'document':
      return 'success'
    case 'category':
      return 'warning'
    case 'tag':
      return 'info'
    default:
      return 'info'
  }
}

// 搜索订阅
function searchSubscriptions() {
  currentPage.value = 1
  fetchSubscriptions()
}

// 按类型筛选
function filterByType() {
  currentPage.value = 1
  fetchSubscriptions()
}

// 分页处理
function handleSizeChange(size) {
  pageSize.value = size
  fetchSubscriptions()
}

function handleCurrentChange(page) {
  currentPage.value = page
  fetchSubscriptions()
}

// 查看订阅详情
async function viewSubscriptionDetail(subscription) {
  currentSubscription.value = { ...subscription }
  
  // 模拟获取通知历史
  notificationHistory.value = Array.from({ length: Math.floor(Math.random() * 5) + 1 }, (_, i) => ({
    time: new Date().getTime() - Math.floor(Math.random() * 10000000),
    content: `通知内容: ${subscription.type === 'document' ? '文档更新' : subscription.type === 'category' ? '分类下有新文档' : '新增标签文档'}`,
    status: Math.random() > 0.2 ? 'success' : 'failure'
  })).sort((a, b) => b.time - a.time) // 按时间降序排序
  
  subscriptionDetailVisible.value = true
}

// 删除订阅
async function deleteSubscription(id) {
  try {
    await ElMessageBox.confirm('确定要删除此订阅吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里替换为实际的API调用
    // await axios.delete(`/api/admin/subscriptions/${id}`)
    
    // 模拟删除成功
    subscriptions.value = subscriptions.value.filter(sub => sub.id !== id)
    total.value--
    
    ElMessage.success('订阅删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Failed to delete subscription:', error)
      ElMessage.error('删除订阅失败')
    }
  }
}

// 发送测试通知
async function sendTestNotification(id) {
  try {
    // 这里替换为实际的API调用
    // await axios.post(`/api/admin/subscriptions/${id}/test-notification`)
    
    // 模拟发送成功
    await new Promise(resolve => setTimeout(resolve, 800))
    
    ElMessage.success('测试通知发送成功')
  } catch (error) {
    console.error('Failed to send test notification:', error)
    ElMessage.error('发送测试通知失败')
  }
}
</script>

<style scoped>
.subscription-management {
  width: 100%;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-filters {
  display: flex;
  gap: 15px;
}

.loading-container, 
.empty-container {
  padding: 40px 0;
  text-align: center;
}

.detail-actions {
  margin: 20px 0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.notification-history {
  margin-top: 30px;
}

.notification-history h3 {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 